package com.xhji.web.config.redis;

import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;

import java.time.Duration;

/**
 * @author xhji
 */
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport{
    @Bean
    public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
        // 初始化一个RedisCacheWriter
        RedisCacheWriter cacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory);

        //设置默认缓存过期时间
        RedisCacheConfiguration defaultCacheConfig=RedisCacheConfiguration.defaultCacheConfig()
                            .entryTtl(Duration.ofHours(1))
                            .serializeKeysWith(RedisTimeCacheManager.STRING_PAIR)
                            .serializeValuesWith(RedisTimeCacheManager.FASTJSON_PAIR);
        return new RedisTimeCacheManager(cacheWriter, defaultCacheConfig);
    }

    @Bean
    @ConditionalOnMissingBean(name = "redisTemplate")
    public RedisTemplate<String,Object> redisTemplate(RedisConnectionFactory factory){
        // 配置redisTemplate
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(factory);
        // key序列化
        redisTemplate.setKeySerializer(RedisTimeCacheManager.STRING_SERIALIZER);
        // value序列化
        redisTemplate.setValueSerializer(RedisTimeCacheManager.FASTJSON_SERIALIZER);
        // Hash key序列化
        redisTemplate.setHashKeySerializer(RedisTimeCacheManager.STRING_SERIALIZER);
        // Hash value序列化
        redisTemplate.setHashValueSerializer(RedisTimeCacheManager.FASTJSON_SERIALIZER);
        // 如果 KeySerializer 或者 ValueSerializer 没有配置，则对应的 KeySerializer、ValueSerializer 才使用这个 Serializer
        redisTemplate.setDefaultSerializer(RedisTimeCacheManager.FASTJSON_SERIALIZER);
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }
}
